//解构表结构数据

/**
 * 解析元数据信息
 * @param {*} script 
 * @returns 
 */
function getTableMateData(script) {
    let mateData = {}
    let mateArray = script.split(" ")
    mateData.metaRowFormat="DYNAMIC"
    mateArray.forEach(row => {
        if (!row.includes("DEFAULT")) {
            let column = row.split("=")
            if(row.includes("COMMENT")){
                mateData.metaComment= replaceSymbol("'",column[1])
            }else {
                let key ='meta'
                column[0].split("_").forEach(str=>{
                    key=`${key}${str.substring(0, 1).toUpperCase()}${str.substring(1, str.length).toLowerCase()}`
                })
                mateData[key] = column[1]
            }
        }
    })
    return mateData
}
/**
 * 解析索引约束信息
 * @param {*} script 
 * @returns 
 */
function getIndexKeyInfo(script) {
    let indexRow = {}
    indexRow.id = getPrimaryKey()
    if(script.includes("UNIQUE")){
        indexRow.keyType="UNIQUE"
    }else if(script.includes("SPATIAL")){
        indexRow.keyType="SPATIAL"
    }else if(script.includes("FULLTEXT")){
        indexRow.keyType="FULLTEXT"
    }else {
        indexRow.keyType="NORMAL"
    }
    if(script.includes("HASH")){
        indexRow.keyMethod="HASH"
    }else {
        indexRow.keyMethod="BTREE"
    }
    if(script.includes("COMMENT")){
        indexRow.keyComment=replaceSymbol("'",script.substring(script.indexOf("COMMENT"),script.length).split(" ")[1])
    }
    indexRow.keyName = replaceSymbol("`",script.substring(script.indexOf("KEY") + 4, script.indexOf("(")).trim())
    indexRow.keyFields = getMiddleContent("(", ")", script)
    return indexRow
}

/**
 * 解析外键约束信息
 * @param {*} script 
 * @param {*} databaseName 
 * @returns 
 */
function getForeignInfo(script,databaseName) {
    let foreignInfo={}
    foreignInfo.id = getPrimaryKey()
    foreignInfo.outsideName =replaceSymbol('`',replaceSymbol("CONSTRAINT",script.substring(0,script.indexOf("FOREIGN"))).trim())
    foreignInfo.deleteEvent ="RESTRICT"
    foreignInfo.updateEvent ="RESTRICT"
    let foreignKeyInfo=script.substring(script.indexOf("KEY ")+4,script.length)
    let onIndex=foreignKeyInfo.indexOf("ON");
    let KeyContent,updateArray
    if(onIndex>-1){
        KeyContent=foreignKeyInfo.substring(0,onIndex)
        let updateInfo=foreignKeyInfo.substring(onIndex,foreignKeyInfo.length)
        updateArray=updateInfo.split(" ON ")
    }else {
        KeyContent=foreignKeyInfo
        updateArray=[]
    }
    updateArray.forEach(item=>{
        if(item.includes("DELETE")){
            foreignInfo.deleteEvent = item.substring(item.indexOf("ETE")+3,item.length).trim();
        }
        if(item.includes("UPDATE")){
            foreignInfo.updateEvent = item.substring(item.indexOf("ATE")+3,item.length).trim();
        }
    })
    KeyContent.split('REFERENCES').forEach(column=>{
        let keyColumnArray = getMiddleContent("(", ")", column,false)
        if (column.indexOf("` (") > -1) {
            let leftIndex = column.indexOf("(")
            let columnDbInfo = column.substring(0, leftIndex).trim().split(".")
            let contentInfo = getMiddleContent("(", ")", column.substring(leftIndex, column.length),false)
            if (columnDbInfo && columnDbInfo.length > 1) {
                foreignInfo.outsideModel = replaceSymbol("`", columnDbInfo[0])
                foreignInfo.outsideParentTable = replaceSymbol("`", columnDbInfo[1])
            }else {
                foreignInfo.outsideModel =databaseName
                foreignInfo.outsideParentTable = replaceSymbol("`", columnDbInfo[0])
            }
            foreignInfo.outsideParentTableFiled = contentInfo
        } else {
            foreignInfo.outsideFields = keyColumnArray
        }
    })
    return foreignInfo
}
/**
 * 解析检查约束
 * @param {*} script 
 * @returns 
 */
function getCheckInfo(script) {
    let checkInfo={}
    let checkIndex=script.indexOf("CHECK");
    checkInfo.id = getPrimaryKey()
    checkInfo.checkName = replaceSymbol('`',replaceSymbol("CONSTRAINT",script.substring(0,checkIndex)).trim())
    checkInfo.checkScript = script.substring(checkIndex+8,script.lastIndexOf(")")-1)
    checkInfo.checkNotRequired = script.includes("NOT ENFORCED")
    return checkInfo
}
/**
 * 去除字符串
 * @param {*} symbol 符号
 * @param {*} str 字符串
 * @returns 
 */
function replaceSymbol(symbol,str) {
    return str.replaceAll(symbol,"")
}

/**
 * 解析字段信息
 * @param {*} start 开始符号
 * @param {*} end 结束符号
 * @param {*} str 字符串
 * @returns 
 */
function getMiddleContent(start,end,str,isSort=true){
    // 假设要截取的字符串为str，开始字符串为start，结束字符串为end
    const startIdx = str.indexOf(start) + start.length;
    const endIdx = str.indexOf(end, startIdx);
    const substr = str.substring(startIdx, endIdx);
    let columnArray = []
    substr.split(",").forEach(keyColumn => {
        let column=replaceSymbol("`", keyColumn.replaceAll(" DESC","").trim())
        if(isSort){
            let columnInfo = {}
            columnInfo.column =column
            if (keyColumn.includes("DESC")) {
                columnInfo.sort = "DESC"
            } else {
                columnInfo.sort = "ASC"
            }
            columnArray.push(columnInfo)
        }else{
            columnArray.push(column)
        }
    })
    return columnArray
}
/**
 * 解析mysql创建表脚本
 * @param {*} createScript 创建脚本
 * @param {*} databaseName 数据库名
 * @param {*} tableName 表名
 * @returns 
 */
export function decomposeCreateTableScript(createScript,databaseName,tableName){
    let tableInfo={}
    let engineIndex=createScript.indexOf('ENGINE')
    let suffix = createScript.substring(engineIndex, createScript.length + 1);//创建脚本的后缀
    tableInfo.metaData=getTableMateData(suffix)
    tableInfo.metaData.tableName=tableName
    let scriptContent = createScript.substring(createScript.indexOf('` (') + 5, engineIndex-2);//创建脚本的内容
    let constraintList = scriptContent.split("\n").filter(row => row.includes("KEY")||row.includes("CHECK"));
    let indexArray=[]
    let primaryArray=[]
    let outsideArray=[]
    let checkArray=[]
    constraintList.forEach(constraint => {
        if(constraint.includes("KEY")){
            if (constraint.includes("PRIMARY")) {
                //主键
                primaryArray=getMiddleContent("(", ")", constraint,false)
            } else if (constraint.includes("FOREIGN")) {
                //外键
                outsideArray.push(getForeignInfo(constraint,databaseName))
            } else {
                //索引
                indexArray.push(getIndexKeyInfo(constraint))
            }
        }else {
            //检查
            checkArray.push(getCheckInfo(constraint))
        }
    })
    tableInfo.indexList=indexArray
    tableInfo.primaryList=primaryArray
    tableInfo.outsideList=outsideArray
    tableInfo.checkList=checkArray
    console.log('tableInfo==',tableInfo)
    return tableInfo
}
    